package com.itheima.server.imp;

import com.itheima.mapper.CategoryMapper;
import com.itheima.pojo.Category;
import com.itheima.server.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<Category> getAll() {
        List<Category> list = categoryMapper.getAll();

        return get(list);
    }

    public List<Category> get(List<Category> list) {
        Map<Integer, Category> map = new HashMap<>();
        List<Category> cg = new ArrayList<>();
        for (Category c : list) {
            map.put(c.getId(), c);
            c.setChildren(new ArrayList<>());
        }
        for (Category c : list) {
            if (c.getParentId() == null || c.getParentId() == 0) {
                cg.add(c);
            } else {
                Category parent = map.get(c.getParentId());
                    parent.getChildren().add(c);

            }
        }
        return cg;
    }
}
